<template>
  <div class="witness-body Workbench">
    <!-- 管理员登录显示的面包屑 -->
    <breadcrumb
      v-if="managerFlag"
      :breadPathList="breadPathList"
      lastBreadTitle="查看见证中任务"
      :showBackBtnFlag="true"
      @handleBack="handleBackFn"
    />
    <!-- 见证员登录显示的面包屑 -->
    <breadcrumb v-else />
    <div class="witness-main">
      <div class="k-header-box">
        <!-- 见证人员 start -->
        <div v-if="!managerFlag">
          <div class="la yout-between">
            <div class="">
              <!-- {{ topTaskYujingData.ZB }} -->
              <el-tabs v-model="topTaskActive" @tab-click="stepsClickFn">
                <el-tab-pane name="ZB">
                  <span slot="label"
                  >招标阶段
                    <i  class="icon-yujing2 font-danger" />
                  </span>
                </el-tab-pane>
                <el-tab-pane name="TB">
                  <span slot="label"
                  >投标阶段
                    <i v-if="topTaskYujingData.TB.isWarn" class="icon-yujing2 font-danger" />
                  </span>
                </el-tab-pane>
                <el-tab-pane name="KB">
                  <span slot="label"
                  >开标阶段
                    <i v-if="topTaskYujingData.KB.isWarn" class="icon-yujing2 font-danger" />
                  </span>
                </el-tab-pane>
                <el-tab-pane v-cloak name="PB">
                  <span slot="label"
                  >评标阶段
                    <i v-if="topTaskYujingData.PB.isWarn" class="icon-yujing2 font-danger" />
                  </span>
                </el-tab-pane>
                <el-tab-pane name="DB">
                  <span slot="label"
                  >定标阶段
                    <i v-if="topTaskYujingData.DB.isWarn" class="icon-yujing2 font-danger" />
                  </span>
                </el-tab-pane>
              </el-tabs>
            </div>
            <div class="add-task-btn">
              <el-button
                v-if="$hasBtnsPerm('BTN_ADD_WITNESS_SUB_TASK')"
                type="primary"
                plain
                size="mini"
                icon="el-icon-circle-plus-outline"
                @click="addTaskFn"
              >
                加入任务
              </el-button>
            </div>
          </div>
          <div class="top-box">
            <div class="xm_info" style="padding: 10px 10px;">
              <el-descriptions title="" :column="2">
                <el-descriptions-item label="标段">{{bd.name}}</el-descriptions-item>
                <el-descriptions-item label="项目">{{bd.xmname}}</el-descriptions-item>
                <el-descriptions-item label="开标室">{{bd.kbroom}}</el-descriptions-item>
                <el-descriptions-item label="评标室">{{bd.pbroom}}</el-descriptions-item>
                <el-descriptions-item label="开标时间">{{bd.kbtime}}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </div>
        <!-- 见证人员 end -->
      </div>
      <div class="layout-wrapper">
        <div class="layout-wrapper layout-row">
          <div :class="['main-side', sideFold ? 'sideFold' : '']">
            <div class="side-content">
              <div class="side-tabs">
                <div class="view" style="margin-top: 15px;">
                  <el-radio-group v-model="tabPosition" @input="viewChange">
                    <el-radio-button label="xm_view">项目视图</el-radio-button>
                    <el-radio-button label="zbr_view">招标人视图</el-radio-button>
                    <el-radio-button label="dl_view">代理机构视图</el-radio-button>
                    <el-radio-button label="tbr_view">投标人视图</el-radio-button>
                  </el-radio-group>
                </div>
                <el-tabs v-model="sideRecordActive" @tab-click="handleClick">
                  <el-tab-pane
                    :disabled="!(currProjectData && currProjectData.witnessStartTime)"
                    label="交易数据"
                    name="first"
                  />
                  <el-tab-pane
                    :disabled="!(currProjectData && currProjectData.witnessStartTime)"
                    label="预警信息"
                    name="second"
                  />
                </el-tabs>
                <!--
            :timestamp="activity.timestamp" -->
              </div>
              <!-- {{ activities }} v-if="sideRecordActive === 'first'"-->
              <div class="timeline-box" v-if="sideRecordActive === 'first'">
                <div class="timeline-box-content">
                  <el-result
                    v-if="activitiesNoDataFlag && !activities.length"
                    icon="empty1"
                    title="暂无数据"
                    :size="180"
                  />
                  <el-scrollbar
                    v-else
                    ref="right"
                    tag="ul"
                    wrap-class="demo-scrollbar-list"
                    wrap-style="color: red;"
                    view-style="font-weight: bold;"
                    view-class="view-box"
                    :noresize="true"
                  >
                    <li class="infinite-list-item">
                      <el-timeline class="" :reverse="reverse">
                        <el-timeline-item
                          v-for="(item, index) in activities"
                          :key="index"
                          :type="
                            item.warningLevel === 'HEIGHT'
                              ? 'danger'
                              : item.warningLevel == 'MIDDLE'
                              ? 'warning'
                              : item.warningLevel == 'LOW'
                              ? 'info'
                              : 'primary'
                          "
                        >
                          <div class="timeline-content">
                            <span v-if="className === item.parentItemCode" :id="item.parentItemCode">
                              <span class="blue">{{ item.itemName }}</span>
                            </span>
                            <span v-else :id="item.parentItemCode" class="ui-mt">{{ item.itemName }}</span>
                            <span :id="item.parentItemCode" class="timeline-tag">{{ item.systemName }}</span>
                            <div
                              v-for="(jtem, jndex) in item.witnessTradeAndWarnDetailInfoList"
                              :key="jndex"
                              :class="
                                jtem.witnessStatus == 'EXCEPTION' && jtem.warningLevel == 'HEIGHT'
                                  ? 'red'
                                  : jtem.witnessStatus == 'EXCEPTION' && jtem.warningLevel == 'LOW'
                                  ? 'yellow'
                                  : 'heise'
                              "
                            >
                              <template v-if="jtem.witnessInfoContent">
                                <div v-for="(ttem, k) in jtem.witnessInfoContent.split('<br/>')" :key="k">
                                  <div style="line-height: 28px;">
                                    <span>{{ ttem }}</span>
                                    &nbsp;&nbsp;
                                    <el-button type="text" size="mini" @click="editRecordClickFn(scope)">评委列表</el-button>
                                  </div>
                                </div>
                                <div>
                                  {{ jtem.witnessStatus == "EXCEPTION" ? "状态异常" : "状态正常" }}
                                </div>
                              </template>
                            </div>
                          </div>
                        </el-timeline-item>
                      </el-timeline>
                    </li>
                  </el-scrollbar>
                </div>
                <div class="timeline-box" v-if="sideRecordActive === 'second'">
                  <div class="timeline-box-content">
                    <el-result
                      v-if="yjActivities.length == 0"
                      icon="empty1"
                      title="暂无数据"
                      :size="180"
                    />
                    <el-scrollbar
                      v-else
                      ref="right"
                      tag="ul"
                      wrap-class="demo-scrollbar-list"
                      wrap-style="color: red;"
                      view-style="font-weight: bold;"
                      view-class="view-box"
                      :noresize="true"
                    >
                    </el-scrollbar>
                  </div>
                </div>
              </div>
              <!-- 分页 -->
              <div v-if="!sideFold" class="layout-footer ui-pt10">
                <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
                <div v-if="sideRecordActive === 'first'" class="fenye">
                  <pagination
                    v-if="pageQueryList.total > pageQueryList.pageSizes[0] && this.pageQueryList.pageSize != -1"
                    :total="pageQueryList.total"
                    :page.sync="pageQueryList.currentPage"
                    :limit.sync="pageQueryList.pageSize"
                    :pageSizes="pageQueryList.pageSizes"
                    layout="total,prev,pager, next"
                    :pager-count="5"
                    @pagination="infoRecordQuerylistFn"
                  />
                </div>
                <div v-else class="fenye">
                  <pagination
                    v-if="pageQueryList.total > pageQueryList.pageSizes[0] && pageQueryList.pageSize != -1"
                    :total="pageQueryList.total"
                    :page.sync="pageQueryList.currentPage"
                    :limit.sync="pageQueryList.pageSize"
                    :pageSizes="pageQueryList.pageSizes"
                    layout="total,prev,pager, next"
                    :pager-count="5"
                    @pagination="warnRecordQuerylistFn"
                  />
                </div>
              </div>
            </div>
            <div class="fold-btn" @click="sideFold = !sideFold">
              <i :class="sideFold ? 'el-icon-arrow-right' : 'el-icon-arrow-left'" />
            </div>
          </div>
          <div class="layout-wrapper layout-body">
            <!-- 见证管理员不显示 -->
            <!-- {{ $route.path === "/Workbench" }} -->
            <div v-if="!managerFlag" class="layout-between ui-mt10">
              <div v-if="true" class="">
                <el-button
                  v-if="$hasBtnsPerm('BTN_TRANSFER_WITNESS_SUB_TASK')"
                  type="primary"
                  size="default"
                  icon="icon-yijiaojianzheng"
                  @click="subtaskClick"
                >
                  移交见证
                </el-button>
                <!-- {{ TASKOBJ.videoWitnessLinkCodeConfig }}
              {{ currProjectData.witnessLinkCode }} -->
                <template>
                  <el-button
                    v-if="$hasBtnsPerm('BTN_VIEW_WITNESS_VIDEO')"
                    type="primary"
                    size="default"
                    icon="icon-chakanshipin1"
                    @click="openMediaFn"
                  >
                    查看视频
                  </el-button>
                </template>
                <el-button
                  v-if="$hasBtnsPerm('BTN_FINISH_WITNESS_SUB_TASK')"
                  type="primary"
                  size="default"
                  icon="icon-jieshujianzheng1"
                  @click="finishWitnessFn"
                >
                  结束见证
                </el-button>
              </div>
              <div class="layout-time">
                <!-- 已见证时长: -->

                <g-timer
                  v-if="true"
                  :type="1"
                  :startTime="currProjectData.witnessStartTime"
                  :endTime="currProjectData.witnessEndTime"
                />
              </div>
            </div>
            <!--
                v-if="currProjectData.projectName" -->
            <div
              v-if="true"
              class="ui-mt10 layout-crad"
            >
              <el-card :class="['box-card', cardVisible ? 'fold-card' : '']">
                <div slot="header" class="clearfix layout-between">
                  <span>新增事项</span>
                  <el-button class="float-right" type="text" size="default" @click="cardVisible = !cardVisible">
                    {{ !cardVisible ? "收起" : "展开" }}
                    <i :class="[cardVisible ? 'el-icon-arrow-down' : 'el-icon-arrow-up']" />
                  </el-button>
                </div>
                <el-form
                  ref="addform"
                  :model="addform"
                  :rules="rules"
                  label-width="120px"
                  :inline="false"
                  size="normal"
                >
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="见证事项" required prop="taskMatterCode">
                        <el-cascader
                          v-model="addform.taskMatterCode"
                          style="width: 100%"
                          option-max-width="300px"
                          :options="witnessMatterOptions"
                          @change="handleChange"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" style="height: 50px">
                      <el-form-item label="状态" prop="status">
                        <i style="color: #e82f2f; position: relative; right: 48px">* </i>
                        <el-radio-group v-model="addform.matterStatus" @change="handleChange">
                          <el-radio label="NORMAL_TYPE"> 正常 </el-radio>
                          <el-radio label="EXCEPTION_TYPE"> 异常 </el-radio>
                        </el-radio-group>
                        <!-- 暂时隐藏预警级别 22-3-25 -->
                        <!-- <el-cascader
                          v-model="addform.warningLevel"
                          style="margin-left: 10px"
                          placeholder="选择等级"
                          option-max-width="150px"
                          class="ui-w120"
                          :options="TASKOBJ.recordExceStatusEnum"
                          :disabled="addform.matterStatus === 'NORMAL_TYPE'"
                          @change="handleErrorLevelChangeFn"
                        /> -->
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <!-- {{ addform.itemCodeList }} -->
                      <el-form-item label="事项说明" required prop="itemCodeList">
                        <el-cascader
                          v-model="addform.itemCodeList"
                          style="width: 50%"
                          option-max-width="300px"
                          :props="{ multiple: false }"
                          :options="matterInstruction"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item label="附件信息" style="width: 50%">
                    <el-upload
                      ref="upload"
                      action=""
                      class="upload"
                      :before-remove="beforeRemoveFn"
                      :on-remove="onRemoveFn"
                      accept=".pdf,.jpg,.png"
                      :http-request="uploadFileFn"
                      :on-success="onUploadSuccessFn"
                      :on-error="onUploadFailedFn"
                    />
                  </el-form-item>
                  <el-form-item label="见证记录" required prop="witnessRecordDesc" style="width: 100%">
                    <el-input
                      v-model.trim="addform.witnessRecordDesc"
                      type="textarea"
                      style="width: 100%"
                      maxlength="200"
                      show-word-limit
                    />
                  </el-form-item>
                </el-form>

                <div slot="footer" class="clear" style="display: flex; justify-content: flex-end">
                  <el-button type="primary" plain size="mini" @click="handleClickAddFn"> 添加附件 </el-button>
                  <el-button :loading="submitLoading" type="primary" @click="submitRecordFn"> 提交 </el-button>
                </div>
              </el-card>
            </div>
            <!-- 见证记录 开始 disabled-->
            <div class="ui-title ui-mt10"> 见证记录 </div>
            <div class="layout-between" style="margin-top: -30px">
              <span>
                <!-- <el-button
              type="primary"
              v-if="
                $hasBtnsPerm('BTN_CONFIRM_WITNESS_RECORD') &&
                  currProjectData.projectName
              "
              size="default"
              @click="allSubmitFn"
              icon="icon-quanbuqueren1"
              >全部确认</el-button
            > -->
              </span>
              <!-- 搜索 见证事项 -->
              <el-input v-model.trim="matterKeyWord" placeholder="事项说明/见证记录" class="ui-w300">
                <el-button slot="append" type="primary" icon="el-icon-search" @click="matterKeyWordFn" />
              </el-input>
            </div>
            <div class="record-box">
              <!-- 列表 -->
              <div class="record-list ui-mt10">
                <div class="table-box">
                  <el-table :data="recordData" border stripe>
                    <el-table-column type="index" align="center" :index="indexFn" label="序号" width="50">
                      <template slot-scope="scope">
                        {{ (pageObj.currentPage - 1) * pageObj.pageSize + scope.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="sortnum" label="编号" width="60" />
                    <!-- <el-table-column
                  prop="data.parentItemName"
                  label="见证事项"
                  min-width="200"
                >
                </el-table-column> -->
                    <el-table-column prop="itemname" label="事项说明" min-width="200">
                      <template slot-scope="scope" row-click>
                        <div v-if="!scope.row.edit">
                          <el-button type="text" size="default" @click="associatedClickFn(scope)">
                            {{ scope.row.itemname }}
                          </el-button>
                        </div>
                        <div v-else>
                          <el-cascader
                            v-model="scope.row.itemcode"
                            style="width: 100%"
                            option-max-width="300px"
                            :props="{ multiple: false }"
                            :options="scope.row.matterInstruction"
                            @change="rowItemCodeChangeFn"
                          />
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="itemstate" label="状态" align="center" width="100">
                      <template slot-scope="scope">
                        <div v-if="!scope.row.edit">
                          <el-tag
                            :type="scope.row.itemstate == 'EXCEPTION_TYPE' ? 'danger' : ''"
                            :color="buildRecordStatusFn(scope.row.data.warningLevel, 'color')"
                            :bg-color="buildRecordStatusFn(scope.row.data.warningLevel, 'bg-color')"
                            :border-color="buildRecordStatusFn(scope.row.data.warningLevel, 'border-color')"
                          >
                            {{ witnessItemStatusFn(scope.row.itemstate) }}
                          </el-tag>
                        </div>
                        <div v-else>
                          <el-select
                            v-model="scope.row.itemstate"
                            value-key=""
                            placeholder=""
                            option-max-width="300px"
                            @change="rowStartusChangeFn(scope)"
                          >
                            <el-option
                              v-for="item in TASKOBJ.witnessItemStatus"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            />
                          </el-select>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column prop="data.witnessRecordDesc" label="见证记录" min-width="150">
                      <template v-if="scope.row.remark" slot-scope="scope">
                        <div v-for="(item, index) in scope.row.remark.split('<br/>')" :key="index">
                          {{ item }}
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="source" label="记录来源" min-width="100" />
                    <el-table-column prop="cretime" label="时间" min-width="100" />
                    <!-- <el-table-column prop="data.source" label="记录人" width="80">
                  </el-table-column> -->
                    <el-table-column prop="qrusername" label="确认人" width="80" />

                    <el-table-column v-if="!managerFlag" label="操作" align="center" width="110">
                      <template slot-scope="scope">
                        <template v-if="!!scope.row.edit">
                          <el-button type="text" size="default" @click="saveRecordClickFn(scope)"> 保存 </el-button>
                          <el-button type="text" size="default" @click="cancelRecordClickFn(scope)"> 取消 </el-button>
                        </template>
                        <div v-else>
<!--                          <template v-for="item in scope.row.pageOpers">-->
                            <!--  -->
                            <el-button
                              type="text"
                              size="default"
                              @click="editRecordClickFn(scope)"
                            >
                              编辑
                            </el-button>
                            <el-button
                              type="text"
                              size="default"
                              @click="submitRecordClickFn(scope)"
                            >
                              确认
                            </el-button>
                            <!-- {{ item.disabled }} -->
                            <el-button
                              type="text"
                              size="default"
                              @click="checkRecordClickFn(scope)"
                            >
                              复核
                            </el-button>
                            <el-button
                              type="text"
                              size="default"
                              @click="deleteRecordClickFn(scope)"
                            >
                              删除
                            </el-button>
<!--                          </template>-->
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <!-- 附件 -->
                <div>
                  <div class="ui-title ui-mt10"> 附件 </div>
                  <!-- 列表 -->
                  <div class="ui-mt10">
                    <div class="table-box">
                      <el-table :data="attachment" border stripe>
                        <el-table-column type="index" align="center" :index="indexFn" label="序号" width="50" />
                        <el-table-column prop="itemName" label="事项说明" align="center" min-width="150" />
                        <el-table-column prop="attachmentName" label="附件名称" min-width="200">
                          <template slot-scope="scope" row-click>
                            <el-button type="text" size="default" @click="handleAttachView(scope)">
                              {{ scope.row.attachmentName }}
                            </el-button>
                          </template>
                        </el-table-column>
                        <el-table-column prop="attachmentType" label="附件类型" align="center" width="100" />

                        <el-table-column prop="createTime" label="接收时间" min-width="120" />
                        <el-table-column label="来源" min-width="100">
                          <template slot-scope="scope">
                            {{ scope.row.isSystem === "NO" ? scope.row.source : scope.row.sysName }}
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="110">
                          <template slot-scope="scope">
                            <el-button type="text" size="default" @click="downloadAttachFn(scope)"> 下载 </el-button>
                            <el-button
                              v-if="scope.row.isSystem === 'NO' && !managerFlag"
                              type="text"
                              size="default"
                              @click="deleteAttachFn(scope)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 分页 -->
            <div class="layout-footer ui-pt10">
              <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
              <pagination
                v-if="pageObj.total > pageObj.pageSizes[0] && this.pageObj.pageSize != -1"
                :total="pageObj.total"
                :page.sync="pageObj.currentPage"
                :limit.sync="pageObj.pageSize"
                :pageSizes="pageObj.pageSizes"
                @pagination="witnessRecordListFn"
              />
            </div>
          </div>
        </div>
        <!-- <div class="" v-else>
      <el-result icon="empty1" title="暂无数据" :size="180"></el-result>
    </div> -->
        <el-dialog title="结束见证" :visible.sync="finishVisible" width="500px" class="cancel-dialog">
          <div class="info-box">
            <i class="el-icon-warning" />
            请确认当前见证的交易活动已结束，确认无误后进行结束见证操作。<br /><br />
            结束见证时将自动执行见证事项【确认】操作。<br />
            结束见证后当前见证子任务不可再次开启见证。
          </div>

          <span slot="footer">
            <el-button type="primary" :loading="cancelLoading" @click="submitCodeDialogFn">确定</el-button>
            <el-button @click="closeCodeDialogFn">取消</el-button>
          </span>
        </el-dialog>
        <!-- 移交见证 -->
        <el-dialog title="移交见证" :visible.sync="yiJiaoVisible" width="500" draggable custom-class="dialog-demo">
          <div> <span class="warning">!</span>移交见证任务后该任务将从当前列表中移除，请确认无误后进行移交。 </div>
          <el-form ref="formSubt" :model="formSubt" label-width="auto" label-max-width="140px" :rules="rulesyj">
            <el-form-item label="移交给" prop="witnessSubTaskIdList">
              <el-select v-model="formSubt.witnessSubTaskIdList" placeholder="请选择" @change="yiJiaoChange">
                <el-option
                  v-for="(item, index) in subtaskList"
                  :key="index"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="移交原因" prop="reason">
              <el-input v-model="formSubt.reason" type="textarea" placeholder="请输入移交原因" />
            </el-form-item>
            <el-form-item class="dialog-footer">
              <span>
                <el-button type="primary" @click="submitYj('formSubt')">确定</el-button>
                <el-button @click="cancelYj('formSubt')">取消</el-button>
              </span>
            </el-form-item>
          </el-form>
        </el-dialog>
        <vCodeDialog
          headerTitle="删除"
          :show="deleteVisible"
          message="请确认删除当前见证记录。"
          @submit="witnessRecordDeleteFn"
          @close="closeDeleteDialogFn"
        />
        <vAddtask :initData="TASKOBJ" :show="addTaskVisible" @submit2="addTaskSubmitFn" @close="closeAddTaskDialogFn" />
        <!--见证记录 编辑、复核 编辑/复核见证事项-->
        <el-dialog
          :title="(checkRecordId ? '复核' : '编辑') + '见证事项'"
          :visible.sync="jzsxVisible"
          width="500px"
          draggable
          custom-class=""
          :before-close="cancelRecordClickFn"
        >
          <!-- <div>
        <span class="warning">!</span>
      </div> -->
          <el-form ref="formJZSX" :model="currentRowData" label-width="auto" label-max-width="140px" :rules="rules">
            <el-form-item label="见证事项">
              {{ currentRowData.parentItemName }}
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="currentRowData.itemStatus" @change="rowStartusChangeFn(currentRowScope)">
                <el-radio label="NORMAL_TYPE"> 正常 </el-radio>
                <el-radio label="EXCEPTION_TYPE"> 异常 </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="事项说明">
              <!-- @change="rowItemCodeChangeFn" -->
              <!-- {{ currentRowData }} -->
              <el-cascader
                v-model="currentRowData.itemCodes"
                style="width: 100%"
                option-max-width="300px"
                :props="{ multiple: false }"
                :options="currentRowScope.matterInstruction"
              />
            </el-form-item>
            <el-form-item label="见证记录">
              <el-input
                v-model.trim="currentRowData.witnessRecordDesc"
                type="textarea"
                placeholder="请输入内容"
                maxlength="200"
                :rows="2"
                show-word-limit
              />
            </el-form-item>

            <el-form-item class="dialog-footer">
              <span>
                <el-button :loading="btnLoading" type="primary" @click="saveRecordClickFn()">保存</el-button>
                <el-button @click="cancelRecordClickFn()">取消</el-button>
              </span>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import gTimer from "@/components/timer.vue";
import vCodeDialog from "@/components/dialog/VerificationCode.vue";
import vAddtask from "@/components/dialog/Addtask.vue";
import {
  moduleInit,
  subtaskListOwner,
  witnessRecordList,
  itemDictList,
  witnessRecordAdd,
  newInfoRecordQuerylist,
  witnessRecordClicks,
  witnessRecordConfirmOne,
  witnessRecordUpdate,
  witnessRecordDelete,
  subtaskFinish,
  warnRecordList,
  subtaskListPart,
  subtaskInfo,
  subtaskPermissionUser,
  subtaskAllocateUser,
  ruleList,
  uploadFile,
  getAttachmentList,
  deleteAttachment,
} from "@/api/api.js";
import {  xmviewList, zbrviewList, dlviewList, tbrviewList} from "@/api/weeon/kbtask.js"
import { FindArrayFn } from "@/utils/utils";
export default {
  components: {gTimer, vCodeDialog, vAddtask },
  data() {
    return {
      taskid: this.$route.query.taskid,
      viewData:{
        xm_view: [],
        zbr_view: [],
        dl_view: [],
        tbr_view: []
      },
      bd: {
        name: '第一标段',
        xmname: '电视村村通、户户通',
        kbroom: '第一开标室',
        pbroom: '第二评标室',
        kbtime: '2024-10-08 10:00:00'
      },
      witnessMatterOptions: [
        {
          value: 'XMVIEW',
          label: '项目视图'
        },
        {
          value: 'TBRVIEW',
          label: '投标人视图'
        }
      ],
      matterInstruction: [
        {
          value: 'KBKS',
          label: '开标是否正常开始'
        },
        {
          value: 'KBJS',
          label: '开标是否正常结束'
        }
      ],
      yjActivities: [],
      activities: [
        /*{
          warningLevel: "NORMAL",
          parentItemCode: "",
          itemName: "开标是否正常开始",
          systemName: "榆林见证",
          witnessTradeAndWarnDetailInfoList: [
            {
              witnessStatus: "NORMAL",
              warningLevel: "NORMAL",
              witnessInfoContent: "2024-10-11 9:02:12 招标代理  公布投标人名单"
            },
            {
              witnessStatus: "NORMAL",
              warningLevel: "NORMAL",
              witnessInfoContent: "2024-10-11 9:02:12 开标   开标地点：1开标室"
            }
          ]
        },
        {
          warningLevel: "NORMAL",
          parentItemCode: "HlTest1010",
          itemName: "开标是否正常结束",
          systemName: "榆林见证",
          witnessTradeAndWarnDetailInfoList: [
            {
              witnessStatus: "NORMAL",
              warningLevel: "NORMAL",
              witnessInfoContent: "2024-10-11 9:02:12 开标结束"
            }
          ]
        }*/
      ],
      recordData: [
        {
          data:{
            recordSortStr: '1',
            itemName: 'itemName',
            itemCodes: 'itemCodes',
            itemStatus: 'NORMAL_TYPE',
            warningLevel: 'LOW',
            witnessRecordDesc: 'witnessRecordDesc',
            source: 'source',
            witnessRecordTime: 'witnessRecordTime',
            confirmUserName: 'confirmUserName'
          }
        },
        {
          data:{
            recordSortStr: '1',
            itemName: 'itemName',
            itemCodes: 'itemCodes',
            itemStatus: 'EXCEPTION_TYPE',
            warningLevel: 'LOW',
            witnessRecordDesc: 'witnessRecordDesc',
            source: 'source',
            witnessRecordTime: 'witnessRecordTime',
            confirmUserName: 'confirmUserName'
          }
        }
      ],
      breadPathList: [
        {
          path: "/WitnessTaskManagement/WitnessTaskView",
          title: "见证任务管理"
        }
      ], // 管理员从“见证任务查看”模块跳转过来时，需要显示的面包屑
      tabPosition: 'xm_view',
      className: "",
      witnessStatus: "",
      cancelLoading: false,
      updateOverFlag: true,
      leftRightBtnFlag: false,
      cardVisible: true,
      topTaskVisible: true,
      yiJiaoVisible: false,
      finishVisible: false,
      deleteVisible: false,
      addTaskVisible: false,
      jzsxVisible: false,
      btnLoading: false,
      checkRecordId: "",
      parentItemCodeGl: "",
      stepActive: 0,
      deleteRow: {},
      deleteIndex: null,
      pageObj: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      pageQueryList: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      formSubt: {
        witnessSubTaskIdList: "",
        reason: "",
        userId: ""
      },
      currProjectData: {
        projectName: "测试项目",
        witnessSubTaskName: "开标任务",
        witnessStartTime: "2024-10-09 10:00:00"
      },
      currentRowData: {
        parentItemName: '开标是否正常开始'
      },
      currentRowScope: {},
      sideRecordActive: "first",
      topTaskActive: "KB",
      submitLoading: false,
      sideFold: false,
      reverse: false,
      TASKOBJ: {
        witnessItemStatus: [
          {
            label: '异常',
            value: 'EXCEPTION_TYPE'
          },
          {
            label: '正常',
            value: 'NORMAL_TYPE'
          }
        ]
      },
      id: "",
      subtaskList: [],

      topTaskAllData: {
        ZB: [],
        TB: [],
        KB: [],
        PB: [],
        DB: []
      },
      topTaskYujingData: {
        ZB: {},
        TB: {},
        KB: {},
        PB: {},
        DB: {}
      },
      topTaskData: [],
      rules: {
        taskMatterCode: [{ required: true, message: "见证事项不能为空", trigger: "blur" }],
        itemCodeList: [{ required: true, message: "事项说明不能为空", trigger: "change" }],
        witnessRecordDesc: [
          {
            required: true,
            message: "见证记录不能为空",
            trigger: "change"
          },
          {
            required: true,
            message: "见证记录不能为空",
            trigger: "blur"
          }
        ]
        // 预警级别校验暂时隐藏
        // status: [
        //   {
        //     message: "选择等级不能为空",
        //     validator: (rule, value, callback) => {
        //       console.log(value);
        //       if (
        //         this.addform.matterStatus !== "NORMAL_TYPE" &&
        //         !this.addform.warningLevel
        //       ) {
        //         callback(new Error("选择等级不能为空"));
        //       } else {
        //         callback();
        //       }
        //     },
        //     trigger: "blur",
        //   }
        // ],
        // keyWord: [{ required: true, message: "key不能为空", trigger: "blur" }],
      },
      ruleForm: {},
      rulesyj: {
        witnessSubTaskIdList: [{ required: true, message: "移交人不能为空", trigger: "blur" }],
        reason: [{ required: true, message: "移交原因不能为空", trigger: "blur" }]
        // witnessSubTaskIdList: [
        //   { required: true, message: "事项说明不能为空", trigger: "change" },
        // ],
      },
      matterKeyWord: "",
      activitiesNoDataFlag: false,
      activitiesOld: [],
      addform: {
        matterStatus: "NORMAL_TYPE",
        taskMatterCode: [],
        itemCodeList: [],
        witnessRecordDesc: "",
        warningLevel: "",
        attachmentList: []
      },
      tableData: [{}],
      taskListFlag: false,
      attachment: [
        {
          itemName: 'itemName',
          attachmentName: 'attachmentName',
          attachmentType: 'attachmentType',
          createTime: 'createTime',
          source: 'source',
          isSystem: 'NO'
        },
        {
          itemName: 'itemName',
          attachmentName: 'attachmentName',
          attachmentType: 'attachmentType',
          createTime: 'createTime',
          source: 'source',
          isSystem: 'NO'
        }
      ],
      subscribedUrlArr: [] // 记录已经订阅的ws的url通道
    };
  },
  computed: {
    managerFlag() {
      // return false
      return this.$store.getters.roleCode === "GDW_R_WITNESS_MANAGER";
      // return this.$store.getters.roleCode==="GDW_R_WITNESS_PERSON"
    },

    /*wsData() {
      return this.$websocket.getters.wsData;
    }*/
  },
  watch: {
    topTaskData() {
      console.log("aaaaaaa");
      // 这里需要设计一下，dom渲染完在计算宽度 by link
      if (this.$refs.refTaskList) {
        this.$nextTick(() => {
          this.leftRightBtnFlag =
            this.$refs.refTaskList && this.$refs.refTaskList.scrollWidth > this.$refs.refTaskList.clientWidth;
        });
      }
    },
    taskListFlag() {
      if (this.$refs.refTaskList) {
        console.log("leftRightBtnFlag", this.$refs.refTaskList.scrollWidth);
        console.log("leftRightBtnFlag", this.$refs.refTaskList.clientWidth);
      }
      setTimeout(() => {
        this.leftRightBtnFlag =
          this.$refs.refTaskList && this.$refs.refTaskList.scrollWidth > this.$refs.refTaskList.clientWidth;
      }, 500);
    }
  },
  async created() {
    console.log("this.$route.query----------------", this.$route);
    this.id = this.$route.query.id || sessionStorage.getItem("witnessSubTaskId");
    this.witnessLinkCode = this.$route.query.type;
    this.xmview();
  },
  beforeDestroy() {
    this.subscribedUrlArr.forEach((url) => {
      // 断开ws订阅通道
      this.$websocket.dispatch("websocket_unsubscribe", url);
    });
  },
  mounted() {
    console.log("${this.id}", this.id);
    this.$nextTick(function () {
      // 代码保证 this.$el 在 document 中
      document.addEventListener("click", (e) => {
        // console.log("e", e.target);
        // console.log("this.$refs.topTaskBox", this.$refs.topTaskBox);
        // console.log("this.$refs.changeTaskBtn", this.$refs.changeTaskBtn);

        if (this.$refs.changeTaskBtn && this.$refs.changeTaskBtn.$el.contains(e.target)) {
          // this.taskListFlag = true;
        } else if (this.$refs.topTaskBox && !this.$refs.topTaskBox.contains(e.target)) {
          this.taskListFlag = false;
        }
      });
    });
  },
  methods: {

    async xmview(){
      debugger
      let p = {taskid: this.taskid}
      const res = await xmviewList(p)
      if (res.stat == 1) {
        this.activities = res.data;
        console.log(res.data)
      }
    },

    async zbrview(){
      debugger
      let p = {taskid: this.taskid}
      const res = await zbrviewList(p)
      if (res.stat == 1) {
        this.activities = res.data;
        console.log(res.data)
      }
    },
    async dlview(){
      debugger
      let p = {taskid: this.taskid}
      const res = await dlviewList(p)
      if (res.stat == 1) {
        this.activities = res.data;
        console.log(res.data)
      }
    },
    async tbrview(){
      debugger
      let p = {taskid: this.taskid}
      const res = await tbrviewList(p)
      if (res.stat == 1) {
        this.activities = res.data;
        console.log(res.data)
      }
    },

    // 视图切换
    viewChange(value){
      this.sideRecordActive = 'first';
      if (value == 'xm_view') {
        this.xmview();
      }else if (value == 'zbr_view') {
        this.zbrview();
      }else if (value == 'dl_view') {
        this.dlview();
      }else if (value == 'tbr_view') {
        this.tbrview();
      }
      // alert('viewChange：' + value);
      // 加载数据
    },
    // 管理员返回方法
    handleBackFn() {
      this.$router.push({ path: "/WitnessTaskManagement/WitnessTaskView" });
    },
    //查询见证状态
    async ruleListFn() {
      try {
        let p = {};
        const res = await ruleList(p);
        if (res.success) {
          this.ruleForm = res.data[0];
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    taskLeftFn() {
      console.log("this.$refs.refTaskList.scrollLeft", this.$refs.refTaskList.scrollLeft);
      console.log("this.$refs.refTaskList.scrollWidth", this.$refs.refTaskList.scrollWidth);
      console.log("this.$refs.refTaskList.clientWidth", this.$refs.refTaskList.clientWidth);

      this.$refs.refTaskList.scrollLeft -= 600;
    },
    taskRightFn() {
      console.log("this.$refs.refTaskList.scrollLeft", this.$refs.refTaskList.scrollLeft);
      this.$refs.refTaskList.scrollLeft += 600;
    },
    // 结束见证弹框事件
    submitCodeDialogFn() {
      this.finishVisible = false;
      this.subtaskFinishFn();
    },
    closeCodeDialogFn() {
      this.finishVisible = false;
      this.cancelLoading = false;
    },
    closeDeleteDialogFn() {
      this.deleteVisible = false;
    },
    closeAddTaskDialogFn() {
      console.log("ccc");

      this.addTaskVisible = false;
    },
    subtaskClick() {
      console.log(this.currProjectData, "666766767676");
      this.subtaskAllocateFn(this.currProjectData.witnessSubTaskId);
    },
    //移交见证
    async subtaskAllocateFn(id) {
      this.yiJiaoVisible = true;
      let p = {
        witnessSubTaskIdList: [id]
      };
      try {
        const res = await subtaskPermissionUser(p);
        if (res.success) {
          this.subtaskList = res.data.data;
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    cancelYj(formSubt) {
      this.$refs[formSubt].resetFields();
      this.formSubt.witnessSubTaskIdList = "";
      this.yiJiaoVisible = false;
    },
    submitYj(formSubt) {
      this.$refs[formSubt].validate((valid) => {
        if (valid) {
          this.subtaskAllocateUserFn();
          this.yiJiaoVisible = false;
        } else {
          return false;
        }
      });
    },
    yiJiaoChange(e) {
      this.formSubt.userId = e;
    },
    async subtaskAllocateUserFn() {
      let p = {
        userId: this.formSubt.userId,
        reason: this.formSubt.reason,
        witnessSubTaskAllocateType: "TRANSFER_ALLOCATE",
        witnessSubTaskIdList: [this.currProjectData.witnessSubTaskId]
      };
      try {
        const res = await subtaskAllocateUser(p);
        if (res.success) {
          this.$message({
            type: "success",
            message: "移交成功",
            single: true
          });
          this.yiJiaoVisible = false;
          this.addTaskSubmitFn("");
          // this.initFn();
          this.formSubt = {};
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    async initFn(ends) {
      // 1、清空左侧列表
      // 2、清空倒计时
      // 3、清空记录
      this.currProjectData = {};
      this.initFromFn();
      // await this.subtaskListOwnerFn();
      // 以下2个接口放到subtaskListPartFn后调用
      // await this.witnessRecordListFn();
      // await this.infoRecordQuerylistFn(); //
      if (this.witnessLinkCode) {
        this.subtaskInfoFn();
        return;
      }
      if (ends === "ends") {
        // 结束见证
        await this.subtaskListPartFn();
      } else {
        await this.subtaskListPartFn("end");
      }

      // this=
      // await this.InitParentCodeFn(); //
    },
    async addTaskSubmitFn(id) {
      console.log("iiiii", id);
      this.id = id;
      sessionStorage.setItem("witnessSubTaskId", this.id);
      this.$router.replace({
        query: {
          id: this.id
        }
      });
      // this.checkRecordFn();
      await this.initFn();
    },
    // 编辑记录
    async editRecordClickFn({ row, $index }) {
      console.log("edit", row, $index);

      this.currentRowData = {
        ...row.data,
        itemCodes: [row.data.itemCode]
      };
      this.currentRowScope = { row, $index };
      this.updateOverFlag = false; //标记ws获取数据后

      let p = {
        parentCode: row.data.parentItemCode,
        itemStatus: row.data.itemStatus
      };

      const data = await this.itemDictListFn(p);
      this.currentRowScope.matterInstruction = data; //
      this.jzsxVisible = true;
      return;
      // this.$set(this.recordData[$index], "edit", true);
      // this.$set(
      //   this.recordData[$index],
      //   "oldData",
      //   JSON.parse(JSON.stringify(this.recordData[$index].data))
      // );
      // this.$set(this.recordData[$index].data, "itemCodes", [
      //   this.recordData[$index].data.itemCode,
      // ]);
      // // this.matterInstruction;//添加用
      // let p = {
      //   parentCode: row.data.parentItemCode,
      //   itemStatus: row.data.itemStatus,
      // };

      // const data = await this.itemDictListFn(p);
      // this.$set(this.recordData[$index], "matterInstruction", data);
    },
    // 保存按钮事件
    async saveRecordClickFn() {
      // console.log("row", row);
      // console.log("row.data.witnessRecordDesc", row.data.witnessRecordDesc);
      let { $index } = { ...this.currentRowScope };
      let row = {
        data: this.currentRowData,
        matterInstruction: this.currentRowScope.matterInstruction
      };
      this.btnLoading = true;
      let msg = "";
      // 判断为空
      if (!row.data.itemCodes.length) {
        msg = "事项说明不能为空！";
      }

      if (!row.data.witnessRecordDesc) {
        msg = "见证记录不能为空！";
      }
      if (msg) {
        this.$message({
          type: "error",
          message: msg,
          single: true
        });
        this.btnLoading = false;
        return;
      }
      console.log("111");

      console.log("this.checkRecordId", this.checkRecordId);
      console.log("row.data.recordId", row.data.recordId);

      // return;
      // if (row.newAdd) {
      // 复核-有两个逻辑
      if (this.checkRecordId) {
        // 复核-编辑人工
        if (this.checkRecordId !== row.data.recordId) {
          this.$set(
            this.recordData[$index].data,
            "itemName",
            FindArrayFn(row.matterInstruction, row.data.itemCodes[0]).label
          );

          await this.witnessRecordUpdateFn($index);
        } else {
          // 复核-保存-调新增
          let itemCodes = row.data.itemCodes;
          // .map((item) => {
          //   return item;
          //   // return item[0];多选
          // });
          // this.$set(this.recordData[$index], "edit", false);
          // v-model="scope.row.data.itemCodes"
          // :options="scope.row.matterInstruction"
          let params = {
            itemCodes,
            recordId: row.data.recordId,
            recordSort: row.data.recordSort,
            itemStatus: row.data.itemStatus,
            witnessRecordDesc: row.data.witnessRecordDesc,
            witnessSubTaskId: this.currProjectData.witnessSubTaskId,
            witnessTaskId: this.currProjectData.witnessTaskId,
            source: this.$store.getters.username || localStorage.getItem("username")
          };
          console.log("params", params);
          // return;
          await this.witnessRecordAddFn(params);
        }
      } else {
        this.$set(
          this.recordData[$index].data,
          "itemName",
          FindArrayFn(row.matterInstruction, row.data.itemCodes[0]).label
        );

        await this.witnessRecordUpdateFn($index);
      }
      // 系统推送的复核、确认按钮删除

      this.jzsxVisible = false;
      this.btnLoading = false;
      this.updateOverFlag = true;
    },
    // 保存按钮事件 old by link
    // saveRecordClickFn({ row, $index }) {
    //   console.log("row", row);
    //   console.log("row.data.witnessRecordDesc", row.data.witnessRecordDesc);
    //   // 判断为空
    //   if (!row.data.itemCodes.length) {
    //     this.$message({
    //       type: "error",
    //       message: "事项说明不能为空！",
    //       single: true,
    //     });
    //     return;
    //   }

    //   if (!row.data.witnessRecordDesc) {
    //     this.$message({
    //       type: "error",
    //       message: "见证记录不能为空！",
    //       single: true,
    //     });
    //     return;
    //   }

    //   if (row.newAdd) {
    //     // 复核-保存-调新增
    //     let itemCodes = row.data.itemCodes.map((item) => {
    //       return item;
    //       // return item[0];多选
    //     });
    //     this.$set(this.recordData[$index], "edit", false);
    //     // v-model="scope.row.data.itemCodes"
    //     // :options="scope.row.matterInstruction"
    //     let params = {
    //       itemCodes,
    //       recordId: row.data.recordId,
    //       recordSort: row.data.recordSort,
    //       itemStatus: row.data.itemStatus,
    //       witnessRecordDesc: row.data.witnessRecordDesc,
    //       witnessSubTaskId: this.currProjectData.witnessSubTaskId,
    //       witnessTaskId: this.currProjectData.witnessTaskId,
    //       source:
    //         this.$store.getters.username || localStorage.getItem("username"),
    //     };
    //     console.log("params", params);

    //     this.witnessRecordAddFn(params);
    //   } else {
    //     this.$set(
    //       this.recordData[$index].data,
    //       "itemName",
    //       FindArrayFn(row.matterInstruction, row.data.itemCodes[0]).label
    //     );

    //     this.witnessRecordUpdateFn($index);
    //   }
    //   // 系统推送的复核、确认按钮删除

    //   this.updateOverFlag = true;
    // },
    // 取消按钮事件
    cancelRecordClickFn() {
      this.jzsxVisible = false;
      this.btnLoading = false;
      this.currentRowData = {};
      this.currentRowScope = {};
      // if (this.recordData[$index].newAdd) {
      //   // 删除新增行
      //   this.recordData.splice($index, 1);
      //   // 取消按钮禁用

      //   // this.recordSaveAndCheckBtnFn({row,$index}, false);
      //   // this.recordData[$index].pageOpers.forEach((item, index) => {
      //   //   if (item.code === "OPERATE_WITNESS_RECORD_CHECK") {
      //   //     this.recordData[$index].pageOpers[index].disabled = false;
      //   //   }
      //   //   if (item.code === "OPERATE_WITNESS_RECORD_SUBMIT") {
      //   //     this.recordData[$index].pageOpers[index].disabled = false;
      //   //   }
      //   // });
      // } else {
      //   console.log("row", row);

      //   // 还原记录
      //   this.$set(
      //     this.recordData[$index],
      //     "data",
      //     JSON.parse(JSON.stringify(row.oldData))
      //   );
      //   this.$set(this.recordData[$index], "edit", false);
      // }
      this.checkRecordId = ""; // 复核有用到
      this.updateOverFlag = true;

      // let o = this.hasRecordDataFn(row, "YES");
      // if (o.f) {
      //   // 按钮启用
      //   this.recordSaveAndCheckBtnFn(o, false);
      // }
      // let f = this.recordData.some((item) => {
      //   return item.edit;
      // });
      // if (!f) {
      //   // this.updateOverFlag = false;
      //   // clearInterval(this.setIntervalFlag);
      //   this.witnessRecordListFn();
      // }
    },
    // 确认
    submitRecordClickFn({ row }) {
      this.$confirm("确认见证记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.currentRowData = row.data;
          this.witnessRecordConfirmOneFn();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 下拉change
    async rowStartusChangeFn({ row, $index }) {
      // row.data
      let p = {
        parentCode: this.currentRowData.parentItemCode,
        itemStatus: this.currentRowData.itemStatus
      };
      const data = await this.itemDictListFn(p);
      this.currentRowData;
      // this.currentRowScope.

      // this.$set(this.recordData[$index].data, "itemCode", "");
      // this.$set(this.recordData[$index].data, "itemName", "");
      // this.$set(this.recordData[$index].data, "itemCodes", []);
      // this.$set(this.recordData[$index], "matterInstruction", data);

      this.$set(this.currentRowData, "itemCode", "");
      this.$set(this.currentRowData, "itemName", "");
      this.$set(this.currentRowData, "itemCodes", []);
      this.$set(this.currentRowScope, "matterInstruction", data);
    },
    rowItemCodeChangeFn() {},
    hasRecordDataFn(row, isSystem = "NO") {
      // 判断手动先添加的，复核到编辑
      let i = null;
      let row2 = null;
      console.log("row.data.itemCode", row.data.itemCode);

      let f = this.recordData.some((item, index) => {
        i = index;
        // console.log("item.data.parentItemCode", item.data.parentItemCode);
        // console.log("item.data.isSystem", item.data.isSystem);
        row2 = item;
        return item.data.parentItemCode === row.data.parentItemCode && item.data.isSystem === isSystem;
      });
      console.log("f", f);
      return { f, row: row2, $index: i };
    },
    recordSaveAndCheckBtnFn({ row, $index }, disabled = false) {
      row.pageOpers.forEach((item, index) => {
        // 复核按钮状态
        if (item.code === "OPERATE_WITNESS_RECORD_CHECK") {
          this.$set(this.recordData[$index].pageOpers[index], "disabled", disabled);
        }
        if (item.code === "OPERATE_WITNESS_RECORD_SUBMIT") {
          this.$set(this.recordData[$index].pageOpers[index], "disabled", disabled);
        }
      });
    },

    // 复核
    async checkRecordClickFn({ row, $index }) {
      // 按钮禁用
      // this.recordSaveAndCheckBtnFn({ row, $index }, true);
      this.checkRecordId = row.data.recordId;
      console.log("this.checkRecordId", this.checkRecordId);

      // 这里复核需要修改，
      // 有相同的记录（系统和人工），则编辑人工记录
      // 只有系统，走新增
      let o = this.hasRecordDataFn(row);
      if (o.f) {
        // this.checkRecordId ="";
        // this.$set(this.recordData[i], "edit", true);
        this.editRecordClickFn(o);
        return;
      }

      this.currentRowData = {
        recordId: row.data.recordId,
        recordSort: row.data.recordSort,
        itemCode: row.data.itemCode,
        itemCodes: [row.data.itemCode],
        itemName: row.data.itemName,
        parentItemCode: row.data.parentItemCode,
        parentItemName: row.data.parentItemName,

        // witnessRecordDesc: row.data.witnessRecordDesc,
        witnessRecordDesc: "",
        itemStatus: row.data.itemStatus
      };
      // 添加一行
      let p = {
        parentCode: row.data.parentItemCode,
        itemStatus: row.data.itemStatus
      };
      const data = await this.itemDictListFn(p);
      this.currentRowScope.matterInstruction = data;

      this.jzsxVisible = true;
      return;
      // 插入新行
      this.recordData.splice($index, 0, {
        data: {
          recordId: row.data.recordId,
          recordSort: row.data.recordSort,
          itemCode: row.data.itemCode,
          itemCodes: [row.data.itemCode],
          itemName: row.data.itemName,
          parentItemCode: row.data.parentItemCode,
          parentItemName: row.data.parentItemName,
          witnessRecordDesc: "",
          itemStatus: row.data.itemStatus
        },
        matterInstruction: data,
        newAdd: true,
        edit: true,
        submit: true,
        pageOpers: [
          // {
          //   code: "OPERATE_WITNESS_RECORD_EDIT",
          //   title: "编辑见证记录",
          //   url: "",
          //   desc: "",
          // },
          // {
          //   code: "OPERATE_WITNESS_RECORD_DELETE",
          //   title: "删除见证记录",
          //   url: "",
          //   desc: "",
          // },
        ]
      });
    },
    deleteRecordClickFn({ row, $index }) {
      // 删除提示
      this.deleteVisible = true;
      this.deleteRow = row;
      this.deleteIndex = $index;
      // this.witnessRecordDeleteFn(row, $index);
    },
    handleClick() {
      /*this.className = "";
      console.log("this.sideRecordActive", this.sideRecordActive);
      if (this.sideRecordActive === "first") {
        this.activities = [].concat(this.activitiesOld);
        this.pageQueryList.currentPage = 1;
        this.infoRecordQuerylistFn();
      } else {
        this.activities = this.activitiesOld.filter((item) => {
          return item.witnessStatus === "EXCEPTION";
        });
        this.pageQueryList.currentPage = 1;
        this.infoRecordQuerylistFn("EXCEPTION");
      }*/
    },
    enterClickFn() {},
    updateClickFn() {},
    async InitParentCodeFn() {
      let p = { parentCode: -1 };
      this.witnessMatterOptions;
      let arr = await this.itemDictListFn(p);
      this.witnessMatterOptions = this.refreshOptionsFn(arr);
    },
    // 刷新见证事项的状态
    refreshOptionsFn(arr) {
      return arr.map((item) => {
        let flag = this.recordDataAll.some((recordItem) => {
          // console.log(recordItem.data.parentItemCode, item.value);
          return recordItem.data.parentItemCode === item.value;
        });
        if (flag) {
          item.disabled = true;
        }
        return item;
      });
    },
    async handleChange() {
      // 预警级别逻辑暂时注释
      // if (this.addform.matterStatus === "NORMAL_TYPE") {
      //   this.$refs.addform.validateField("status");
      // }
      /*this.addform.itemCodeList = [];
      console.log("this.addform.taskMatterCode", this.addform.taskMatterCode);

      if (this.addform.taskMatterCode.length > 0 && this.addform.taskMatterCode[0]) {
        // this.$refs["addform"].resetFields();
        let p = {
          parentCode: this.addform.taskMatterCode[0] || -1,
          itemStatus: this.addform.matterStatus
        };
        // if (p.parentCode !=== -1) {
        // p.itemStatus = this.addform.matterStatus;
        // }
        this.matterInstruction = await this.itemDictListFn(p);
        console.log("this.matterInstruction", this.matterInstruction);
        console.log("this.addform.itemCodeList", this.addform.itemCodeList);
        if (this.matterInstruction && this.matterInstruction[0]) {
          this.addform.itemCodeList = [this.matterInstruction[0].value];
        }
      }*/
    },
    handleErrorLevelChangeFn() {
      this.$refs.addform.validateField("status");
    },
    allSubmitFn() {
      this.witnessRecordClicksFn();
    },
    // 加入任务
    addTaskFn() {
      this.addTaskVisible = true;
    },
    // 记录状态
    witnessDataStatusFn(val) {
      let array = this.TASKOBJ.witnessDataStatus;
      let obj = FindArrayFn(array, val) || {};
      return obj.label;
    },
    witnessItemStatusFn(val) {
      debugger
      let array = this.TASKOBJ.witnessItemStatus;
      let obj = FindArrayFn(array, val) || {};
      return obj.label;
    },
    async projectClickFn(data, i) {
      console.log("i", i);

      this.currProjectData = data;
      this.topTaskData.forEach((item, index) => {
        if (i === index) {
          sessionStorage.setItem("witnessSubTaskId", item.witnessSubTaskId);
          this.id = item.witnessSubTaskId;
          this.$set(this.topTaskData[index], "active", "active");
        } else {
          this.$set(this.topTaskData[index], "active", "");
        }
      });
      // 表单重置，放到checkRecordFn中

      await this.checkRecordFn(); //选中
      // //新增事项
      // await this.witnessRecordListFn();
      // await this.infoRecordQuerylistFn();
      // await this.initFn();
    },
    // 初始化模块
    async moduleInitFn() {
      let p = { moduleName: "TASK" };
      try {
        const res = await moduleInit(p);
        if (res.success) {
          this.TASKOBJ = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 确认-记录
    async witnessRecordConfirmOneFn() {
      // recordId 见证记录主键id，修改依据
      let p = {
        // witnessSubTaskId: this.id,
        recordId: this.currentRowData.recordId
      };
      try {
        const res = await witnessRecordConfirmOne(p);
        if (res.success) {
          // this.pageObj.currentPage = 1; // 当前页数
          // this.witnessRecordListFn();
          this.$message({
            type: "success",
            message: res.message || "操作成功",
            single: true
          });
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 全部确认-记录
    async witnessRecordClicksFn() {
      // recordId 见证记录主键id，修改依据
      let p = {
        witnessSubTaskId: this.id
      };
      try {
        const res = await witnessRecordClicks(p);
        if (res.success) {
          this.pageObj.currentPage = 1; // 当前页数
          // this.witnessRecordListFn();
          this.$message({
            type: "success",
            message: res.message || "操作成功",
            single: true
          });
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    openMediaFn() {
      // zhl见证项目2022-03-04-code-11-002
      // DB
      // console.log(" this.currProjectData", this.currProjectData);
      let { bidSectionCode, witnessLinkCode, projectCode } = this.currProjectData;
      window.open(
        `/witness/#/media?bidSectionCode=${bidSectionCode}&witnessLinkCode=${witnessLinkCode}&projectCode=${projectCode}`,
        "witness_media"
      );
    },
    finishWitnessFn() {
      // 这块要和需求沟通：在什么情况下可以结束
      // 先把复核作为条件
      // let flag = this.recordData.some((item) => {
      //   return item.pageOpers.some((val) => {
      //     // OPERATE_WITNESS_RECORD_SUBMIT 确认
      //     // OPERATE_WITNESS_RECORD_CHECK
      //     return val.code === "OPERATE_WITNESS_RECORD_SUBMIT";
      //   });
      // });

      // if (flag) {
      //   this.$message({
      //     type: "error",
      //     message: "有未确认的见证记录",
      //     single: true,
      //   });
      //   return;
      // }
      this.finishVisible = true;

      // this.refreshCode();

      //       this.$confirm(
      //         `请确认当前见证的交易活动已结束，确认无误后进行结束见证操作。
      // 结束见证时将自动执行见证事项【确认】操作。
      // 结束见证后当前见证子任务不可再次开启见证。`,
      //         "提示",
      //         {
      //           confirmButtonText: "确定",
      //           cancelButtonText: "取消",
      //           type: "warning",
      //         }
      //       )
      //         .then(() => {
      //           this.submitCodeDialogFn();
      //           // this.$message({
      //           //   type: 'success',
      //           //   message: '删除成功!'
      //           // });
      //         })
      //         .catch(() => {
      //           // this.$message({
      //           //   type: 'info',
      //           //   message: '已取消删除'
      //           // });
      //         });
    },
    // 更新选项卡的灯泡
    updateIsWarnFn() {
      let jylcType = this.topTaskActive;
      let flag = false;
      if (this.topTaskData.length) {
        jylcType;
        flag = this.topTaskData.some((item) => {
          return item.isWarn;
        });
      }

      this.topTaskYujingData[jylcType].isWarn = flag;
    },
    //  结束见证row, index
    async subtaskFinishFn() {
      let p = {
        witnessSubTaskId: this.id
      };
      try {
        const res = await subtaskFinish(p);
        if (res.success) {
          this.$message({
            type: "success",
            message: res.message || "操作成功",
            single: true
          });

          // 预警更新
          // this.updateIsWarnFn();
          // 只有一条时，结束见证，记录后为空
          if (this.topTaskData.length === 1) {
            this.topTaskYujingData[this.topTaskActive].isWarn = false;
            this.attachment = [];
          }
          this.addTaskSubmitFn("");
          // this.initFn("ends");
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 记录-删除
    async witnessRecordDeleteFn(row, index) {
      // recordId 见证记录主键id，修改依据
      // witnessRecordDesc 见证记录描述
      // itemStatus 见证事项状态（  NORMAL_TYPE("正常类型"),EXCEPTION_TYPE("异常类型") ）
      // itemCode 见证事项编码
      row = this.deleteRow;
      index = this.deleteIndex;
      let p = [row.data.recordId];
      try {
        const res = await witnessRecordDelete(p);
        if (res.success) {
          this.deleteVisible = false;

          // this.witnessRecordListFn(); //更新列表
          this.$delete(this.recordData, index);
          this.$message({
            type: "success",
            message: res.message || "删除成功",
            single: true
          });
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 保存-更新
    async witnessRecordUpdateFn(index) {
      // recordId 见证记录主键id，修改依据
      // witnessRecordDesc 见证记录描述
      // itemStatus 见证事项状态（  NORMAL_TYPE("正常类型"),EXCEPTION_TYPE("异常类型") ）
      // itemCode 见证事项编码

      let p = {
        recordId: this.currentRowData.recordId,
        witnessRecordDesc: this.currentRowData.witnessRecordDesc,
        itemStatus: this.currentRowData.itemStatus,
        itemCodes: [this.currentRowData.itemCode]
      };
      if (this.checkRecordId) {
        p.checkRecordId = this.checkRecordId;
      }
      if (this.currentRowData.itemCodes) {
        p.itemCodes = this.currentRowData.itemCodes || [this.currentRowData.itemCode];
      }
      try {
        const res = await witnessRecordUpdate(p);
        if (res.success) {
          this.$set(this.recordData[index], "edit", false);
          this.$message({
            type: "success",
            message: res.message || "操作成功",
            single: true
          });
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
      this.checkRecordId = "";
    },
    // 见证-全部信息
    async infoRecordQuerylistFn(EXCEPTION) {
      this.activities = [];
      // this.pageQueryList.pageSize = -1;
      let p = {
        // currentPage: this.pageQueryList.currentPage, // 当前页数
        // pageSize: this.pageQueryList.pageSize, // 每页条数
        // pageSize: -1, // 每页条数
        witnessSubTaskId: this.id,
        witnessStatus: EXCEPTION
      };

      this.activitiesNoDataFlag = true;
      if (!this.id) {
        return;
      }
      try {
        const res = await newInfoRecordQuerylist(p);
        if (res.success) {
          this.activitiesNoDataFlag = !res.data.length;
          // this.activitiesNoDataFlag = false;
          this.activities = res.data;
          // this.pageQueryList.total = res.data.pageBean.count;
          this.activitiesOld = [].concat(res.data);
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 见证-预警信息
    async warnRecordQuerylistFn() {
      // witnessStatus: "EXCEPTION"
      // 后端接口合并
      this.infoRecordQuerylistFn("EXCEPTION");
      return;
      // this.activities = [];
      // // this.pageQueryList.pageSize = -1;
      // let p = {
      //   currentPage: this.pageQueryList.currentPage, // 当前页数
      //   pageSize: this.pageQueryList.pageSize, // 每页条数
      //   // pageSize: -1, // 每页条数
      //   witnessSubTaskId: this.id
      // };

      // this.activitiesNoDataFlag = true;
      // if (!this.id) {
      //   return;
      // }
      // try {
      //   const res = await warnRecordList(p);
      //   if (res.success) {
      //     this.activitiesNoDataFlag = !res.data.length;
      //     this.activities = res.data;
      //     // this.pageQueryList.total = res.data.pageBean.count;
      //     this.activitiesOld = [].concat(res.data.data);
      //   } else {
      //     this.$message({
      //       type: "error",
      //       message: res.message || "获取数据失败，请稍后再试",
      //       single: true
      //     });
      //   }
      // } catch (err) {
      //   console.error(err);
      //   this.$message({
      //     type: "error",
      //     message: "获取数据失败，请稍后再试",
      //     single: true
      //   });
      // }
    },
    // 见证事项-列表
    async itemDictListFn(p = {}) {
      // let p = {
      //   parentCode: this.addform.taskMatterCode[0] || -1,
      // };
      // if (p.parentCode !== -1) {
      //   p.itemStatus = this.addform.matterStatus;
      // }
      if (!this.id) {
        return;
      }
      p.witnessSubTaskId = this.id;
      try {
        const res = await itemDictList(p);
        if (res.success) {
          return res.data.map((item) => {
            return { label: item.itemName, value: item.itemCode };
          });
          if (p.parentCode === -1) {
            this.witnessMatterOptions = res.data.map((item) => {
              return { label: item.itemName, value: item.itemCode };
            });
          } else {
            this.matterInstruction = res.data.map((item) => {
              return { label: item.itemName, value: item.itemCode };
            });
          }
          // this.TASKOBJ = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 见证事项-提交
    async submitRecordFn() {
      this.$refs.addform.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.witnessRecordAddFn();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 见证事项-新增
    async witnessRecordAddFn(params) {
      //       dataStatus INVALID
      // 枚举值: INVALID,VALID,TEMP,DELETE,ARCHIVE
      // itemCode 见证事项编码
      // itemStatus NORMAL_TYPE
      // 见证事项状态 枚举值: NORMAL_TYPE,EXCEPTION_TYPE
      // source 见证记录来源
      // witnessRecordDesc 见证记录描述
      // witnessRecordTime 记录时间
      // witnessSubTaskId 见证子任务id
      // witnessTaskId
      let p = {};
      if (params) {
        // 复核调新增
        p = params;
      } else {
        let itemCodes = this.addform.itemCodeList.map((item) => {
          return item;
          // return item[0];多选
        });
        p = {
          itemCodes,
          itemStatus: this.addform.matterStatus,
          witnessRecordDesc: this.addform.witnessRecordDesc,
          warningLevel: this.matterStatus === "NORMAL_TYPE" ? "" : "HEIGHT",
          // 预警级别暂时写死 22-3-25
          // warningLevel: this.addform.warningLevel[0],
          attachmentList: this.addform.attachmentList.map((item) => item.attachId),
          witnessSubTaskId: this.currProjectData.witnessSubTaskId,
          witnessTaskId: this.currProjectData.witnessTaskId,
          source: this.$store.getters.username || localStorage.getItem("username")
        };
      }

      try {
        const res = await witnessRecordAdd(p);
        if (res.success) {
          // this.addform.itemCodeList = [];
          if (!params) {
            this.addform.witnessRecordDesc = "";
            this.addform.matterStatus = "NORMAL_TYPE";
            this.addform.warningLevel = "";
            this.addform.attachmentList = [];
            this.matterInstruction = [];
            this.$refs["addform"].resetFields();
            this.$refs["upload"].clearFiles();
            this.pageObj.currentPage = 1; // 当前页数
          }

          // if (params) {
          // } else {
          // }
          // this.pageObj.pageSize, // 每页条数
          this.witnessRecordListFn(); //更新列表 1、添加后刷新；2、复核保存后刷新
          this.$message({
            type: "success",
            message: res.message || "添加成功",
            single: true
          });
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }

      this.submitLoading = false;
    },
    // 招投开评定切换
    async stepsClickFn(tab) {
      debugger
      if (tab.name == 'PB') {
        this.$router.push("/PbTask");
      }

      /*this.currProjectData = {};

      // // 初始化 表单
      this.initFromFn();
      let i = tab.index;
      let key = this.topTaskKeys[i];
      if (this.topTaskAllData[key]) {
        // this.stepActive = i;
        // this.topTaskKeys[i];
        // 选中任务
        this.topTaskData = this.topTaskAllData[key];
        if (this.topTaskData.length) {
          this.id = this.topTaskData[0].witnessSubTaskId;
          sessionStorage.setItem("witnessSubTaskId", this.id);
        } else {
          this.id = "";
          sessionStorage.setItem("witnessSubTaskId", this.id);
        }

        this.$router.replace({
          query: {
            id: this.id
            // type: this.id,
          }
        });
        if (this.id) {
          // 选中项目
          await this.checkRecordFn();
        }
      } else {
      }*/
    },
    //管理员-查看任务
    async subtaskInfoFn() {
      let p = {
        witnessSubTaskId: this.id,
        witnessLinkCode: this.witnessLinkCode
      };
      const res = await subtaskInfo(p);
      console.log("res", res);

      if (res.success) {
        this.currProjectData = res.data;
        // 管理员监听
        this.webSocketTaskFn([res.data]);
        // 侧边栏、和列表接口
        await this.witnessRecordListFn();
        await this.infoRecordQuerylistFn(); //
      }
    },
    async webSocketTaskFn(data) {
      data.forEach((item) => {
        console.log("订阅witnessSubTaskId", item.witnessSubTaskId);
        // 订阅消息监听
        let url = `/ws/witness/info/${item.witnessSubTaskId}`;
        if (this.subscribedUrlArr.indexOf(url) === -1) {
          this.$websocket.dispatch("websocket_subscribe", `/ws/witness/info/${item.witnessSubTaskId}`);
          this.subscribedUrlArr.push(url);
        }
      });
    },

    // 见证人员-任务列表 /gtv/witness/subtask/list
    async subtaskListPartFn(end) {
      this.topTaskData = [];
      try {
        // let obj = {};
        let p = {
          // currentPage: this.pageObj.currentPage, // 当前页数
          pageSize: -1, // 每页条数
          // industryList, // 行业类型
          // industryTypeList, // 行业类型
          witnessSubTaskStatus: "WITNESSING" // 见证状态
          // witnessSubTaskId: this.id,
          // search: this.formSearch.keyWord, // 搜索
        };

        if (end === "end") {
          p.witnessSubTaskId = this.id;
        }
        const res = await subtaskListPart(p);
        if (res.success) {
          this.topTaskAllData = {
            ZB: res.data["ZB"] || [],
            TB: res.data["TB"] || [],
            KB: res.data["KB"] || [],
            PB: res.data["PB"] || [],
            DB: res.data["DB"] || []
          };
          await this.topTaskAllDataFn(); // 添加 jylcType 属性
          this.topTaskKeys = Object.keys(this.topTaskAllData);
          console.log("this.topTaskKeys", this.topTaskKeys);
          await this.webSocketTaskFn(this.topTaskAllData["ZB"]);
          await this.webSocketTaskFn(this.topTaskAllData["TB"]);
          await this.webSocketTaskFn(this.topTaskAllData["KB"]);
          await this.webSocketTaskFn(this.topTaskAllData["PB"]);
          await this.webSocketTaskFn(this.topTaskAllData["DB"]);

          // this.topTaskData = res.data[this.topTaskKeys[0]];
          // this.topTaskData = this.topTaskAllData.ZB;
          this.topTaskData = this.topTaskAllData[this.topTaskActive];
          if (!this.id && this.topTaskData.length) {
            this.id = this.topTaskData[0].witnessSubTaskId;
            sessionStorage.setItem("witnessSubTaskId", this.id);
          }

          // this.$router.replace({
          //   query: {
          //     id: this.id,
          //   },
          // });
          // if (this.$route.path === "/Workbench") {
          // 选中任务
          await this.checkRecordFn();
          // }
        } else {
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    async topTaskAllDataFn() {
      let ok = Object.keys(this.topTaskAllData);
      let ov = Object.values(this.topTaskAllData);
      let arr = [];
      ok.forEach((item, index) => {
        ov[index].forEach((vitem) => {
          vitem.jylcType = item; //改变源对象的属性
          if (vitem.isWarn) {
            this.topTaskYujingData[item].isWarn = true;
          }
        });
        arr = arr.concat(ov[index]);
      });
      console.log("ov", ov);
      console.log("ov", arr);

      this.topTaskAllArr = arr;

      return;
    },
    initFromFn() {
      this.recordData = [];
      this.activities = [];
      this.sideRecordActive = "first";
      this.pageObj.currentPage = 1;
      this.pageQueryList.currentPage = 1;
      this.submitLoading = false;
      // 初始化 表单
      this.addform.taskMatterCode = "";
      this.addform.matterStatus = "NORMAL_TYPE";
      this.addform.witnessRecordDesc = "";
      this.addform.itemCodeList = [];
      this.addform.warningLevel = "";
      this.witnessMatterOptions = [];
      this.matterInstruction = [];

      this.$refs["addform"] && this.$refs["addform"].resetFields();
    },
    // 选中任务
    async checkRecordFn() {
      // console.log("ov", this.topTaskAllArr);
      // this.topTaskAllData[this.topTaskActive];
      this.initFromFn();
      let currTask = this.topTaskAllArr.filter((item) => {
        return item.witnessSubTaskId === this.id;
      });
      console.log("ov", currTask);

      console.log("ov", this.topTaskData);
      // let currF = this.topTaskData.some((item) => {
      //   return item.witnessSubTaskId === this.id;
      // });

      if (currTask.length === 0) {
        this.id = "";
        sessionStorage.setItem("witnessSubTaskId", "");
        if (this.$route.query.id !== this.id) {
          this.$router.replace({
            query: {
              id: this.id
              // type: this.id,
            }
          });
        }
        return;
      } else {
        this.topTaskActive = currTask[0].jylcType;
        this.topTaskData = this.topTaskAllData[this.topTaskActive];
      }

      // let flag = "";
      let i = 0;
      this.topTaskData.forEach((item, index) => {
        if (this.id === item.witnessSubTaskId) {
          i = index;
          // this.$set(this.topTaskData[index], "active", "active");
        } else {
          this.$set(this.topTaskData[index], "active", "");
        }
      });
      console.log("sssss", i);

      this.currProjectData = this.topTaskData[i] || {};
      // id 没有找到走这里
      this.$set(this.topTaskData[i], "active", "active");
      // this.$set(this.topTaskData[i], "danger", "");
      this.$set(this.topTaskData[i], "isWarn", false);
      // let jylcType = this.topTaskData[i].jylcType;
      // let flag = this.topTaskData.some((item) => {
      //   return item.isWarn;
      // });
      // this.topTaskYujingData[jylcType].isWarn = flag;
      // 更新选项卡的灯泡
      // this.updateIsWarnFn();

      this.id = this.topTaskData[i].witnessSubTaskId;

      sessionStorage.setItem("witnessSubTaskId", this.id);
      if (this.$route.query.id !== this.id) {
        // url跳转
        this.$router.replace({
          query: {
            id: this.id,
            type: this.witnessLinkCode
          }
        });
      }

      // if (this.id && this.id === this.$route.query.id) {
      //   this.topTaskData.forEach((item) => {
      //     console.log("订阅witnessSubTaskId", item.witnessSubTaskId);
      //     // 订阅消息监听
      //     let url = `/ws/witness/info/${item.witnessSubTaskId}`;
      //     if (this.subscribedUrlArr.indexOf(url) === -1) {
      //       this.$websocket.dispatch(
      //         "websocket_subscribe",
      //         `/ws/witness/info/${item.witnessSubTaskId}`
      //       );
      //       this.subscribedUrlArr.push(url);
      //     }
      //   });
      // } else {
      // }
      // 侧边栏、和列表接口
      // await this.witnessRecordListFn();
      // await this.infoRecordQuerylistFn(); //
    },
    // 可操作子任务列表
    async subtaskListOwnerFn() {
      try {
        const res = await subtaskListOwner();
        if (res.success) {
          this.topTaskData = res.data.data;
          if (!this.topTaskData.length) {
            return;
          }
          console.log(
            "sssss",
            res.data.data.some((item) => {
              console.log(item.witnessSubTaskId, this.id);

              return item.witnessSubTaskId === this.id;
            })
          );

          if (
            res.data.data.some((item) => {
              return item.witnessSubTaskId === this.id;
            })
          ) {
            // this.id = this.$route.query.id || this.id;
            this.currProjectData = res.data.data.filter((item, index) => {
              console.log("this.id", this.id);
              console.log("item.witnessSubTaskId", item.witnessSubTaskId);

              if (this.id === item.witnessSubTaskId) {
                console.log("index", index);

                this.$set(this.topTaskData[index], "active", "active");
              }
              return this.id === item.witnessSubTaskId;
            })[0];
          } else {
            // if (this.topTaskData.length) {
            this.currProjectData = res.data.data[0] || {};
            this.$set(this.topTaskData[0], "active", "active");
            this.id = this.topTaskData[0].witnessSubTaskId;
            // }
          }
          console.log("currProjectData", this.currProjectData);

          if (this.id && this.id === this.$route.query.id) {
          } else {
            // url跳转
            this.$router.replace({
              query: {
                id: this.id
              }
            });
          }
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 见证和交易数据关联
    associatedClickFn(row) {
      this.witnessStatus = "";
      this.className = "";
      let code = row.row.data;
      if (code.isSystem === "YES") {
        this.activities.map((item, index) => {
          if (code.parentItemCode === item.parentItemCode) {
            this.className = item.parentItemCode;
            document.getElementById(code.parentItemCode).scrollIntoView();
          }
        });
      }
    },
    matterKeyWordFn() {
      // this.recordData = this.recordDataOld.filter((item) => {
      //   return (
      //     item.data.parentItemName &&
      //     item.data.parentItemName.indexOf(this.matterKeyWord) > -1
      //   );
      // });

      this.pageObj.currentPage = 1; // 当前页数
      this.witnessRecordListFn();
    },
    indexFn(index) {
      return index + 1 + (this.pageObj.currentPage - 1) * this.pageObj.pageSize;
    },
    // 见证记录-所有-添加时的禁用属性
    async witnessRecordListAllFn() {
      if (!this.id) {
        reutrn;
      }
      let p = {
        witnessSubTaskId: this.id
      };
      this.recordDataAll = [];
      try {
        const res = await witnessRecordList(p);
        if (res.success) {
          this.recordDataAll = res.data.result;
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 见证记录
    async witnessRecordListFn() {
      this.recordData = [];
      this.checkRecordId = "";
      this.pageObj.pageSize = -1;
      let p = {
        currentPage: this.pageObj.currentPage, // 当前页数
        pageSize: this.pageObj.pageSize, // 每页条数
        // pageSize: -1, // 每页条数
        witnessSubTaskId: this.id
      };
      if (this.matterKeyWord) {
        p.itemName = this.matterKeyWord;
      }
      if (!this.id) {
        return;
      }
      try {
        const res = await witnessRecordList(p);
        this.getAttachmentListFn();
        if (res.success) {
          if (res.data.data.length === 0 && this.pageObj.currentPage !== 1) {
            console.log("见证记录重复");

            this.pageObj.currentPage = 1;
            this.$nextTick(() => {
              this.witnessRecordListFn();
            });
            return;
          }
          this.pageObj.total = res.data.pageBean.count;
          this.recordDataOld = res.data.result;
          if (!this.managerFlag) {
            this.recordData = res.data.result;
          } else {
            this.recordData = res.data.result.map((item) => {
              item.pageOpers = [];
              return item;
            });
          }

          if (p.pageSize === -1) {
            // 拉取所有见证记录，用于添加时的禁用属性
            await this.witnessRecordListAllFn();
            await this.InitParentCodeFn(); //
          }
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (error) {
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },

    async getAttachmentListFn() {
      try {
        if (!this.id) return;
        const p = {
          witnessSubTaskId: this.id
        };
        const res = await getAttachmentList(p);
        if (res.success) {
          this.attachment = res.data.data;
        }
      } catch (error) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },

    buildRecordStatusFn(warningLevel, type) {
      // console.log(warningLevel);
      return;
      if (!warningLevel || !type) {
        return "";
      }
      const statusObj = {
        color: {
          HEIGHT: "#E82F2F",
          MIDDLE: "#FC9306",
          LOW: "#EAB909"
        },
        "bg-color": {
          HEIGHT: "rgba(232, 47, 47, 0.1)",
          MIDDLE: "rgba(252, 147, 6, 0.1)",
          LOW: "rgba(233, 193, 46, 0.1)"
        },
        "border-color": {
          HEIGHT: "rgba(232, 47, 47, 0.4)",
          MIDDLE: "rgba(252, 147, 6, 0.3)",
          LOW: "rgba(234, 185, 9, 0.3)"
        }
      };
      return statusObj[type][warningLevel] || "";
    },

    // 文件相关
    beforeRemoveFn(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });
    },

    onRemoveFn(file, fileList) {
      for (let [index, item] of this.addform.attachmentList.entries()) {
        if (item.uid === file.uid) {
          this.addform.attachmentList.splice(index, 1);
          return;
        }
      }
    },

    async uploadFileFn(params) {
      debugger
      try {
        const form = new FormData();
        form.append("file", params.file);
        const res = await uploadFile(form);
        if (res.success) {
          this.addform.attachmentList.push({
            ...params.file,
            attachId: res.data
          });
        }
      } catch (error) {
        console.error(err);
        this.$message({
          type: "error",
          message: "上传文件失败，请稍后再试",
          single: true
        });
      }
    },

    onUploadSuccessFn(response, file, fileList) {
      this.$message({
        type: "success",
        message: "上传文件成功!",
        single: true
      });
    },

    onUploadFailedFn(err, file, fileList) {
      this.$message({
        type: "error",
        message: "上传文件失败，请稍后再试",
        single: true
      });
    },

    handleClickAddFn() {
      document.getElementsByClassName("el-upload__input")[0].click();
    },

    downloadAttachFn(scope) {
      const downloadUrl =
        scope.row.isSystem === "NO"
          ? `${process.env.VUE_APP_API}/attach/download?attachId=${scope.row.attachmentPlatformId}`
          : scope.row.attachmentUrl;
      let name = scope.row.attachmentName;
      const downloadRes = async () => {
        let response = await fetch(downloadUrl); // 内容转变成blob地址
        let blob = await response.blob(); // 创建隐藏的可下载链接
        let objectUrl = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.href = objectUrl;
        a.download = `${scope.row.attachmentName}.${scope.row.attachmentType}`;
        a.click();
        a.remove();
      };
      downloadRes();
    },

    handleAttachView(scope) {
      if (scope.row.isSystem === "NO") {
        this.downloadAttachFn(scope);
      } else {
        window.open(scope.row.attachmentUrl);
      }
    },

    async deleteAttachFn(scope) {
      try {
        this.$confirm("确定删除该条附件吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            const p = {
              attachmentPlatformId: scope.row.attachmentPlatformId
            };
            console.log("come in");
            const res = await deleteAttachment(p);
            console.log(res);
            if (res.success) {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.witnessRecordListFn(); // 刷新列表
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } catch (err) {
        this.$message({
          type: "error",
          message: "删除失败，请稍后再试",
          single: true
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.Workbench .witness-main {
  padding: 10px;
}
.layout-wrapper {
  font-size: 14px;
  .el-scrollbar {
    overflow: inherit !important;
  }
  .main-side {
    display: flex;
    // overflow: auto;
    position: relative;
    margin-right: 10px;
    width: 534px;
    border-right: 1px solid $line;
    // flex-direction: row;
    &.sideFold {
      width: 0px;
      overflow: revert;
      .side-content {
        display: none;
      }
      .fold-btn {
        right: -10px;

        border-radius: 0 10px 10px 0;
      }
      .timeline-box,
      .el-tabs {
        display: none;
      }
    }
    .side-content {
      // height: 0;
      display: flex;
      flex: 1;
      flex-direction: column;
      width: 100%;
      // .side-tabs {
      //   // width: 100%;
      //   // height: 100%;
      //   // display: flex;
      //   // flex-direction: column;
      // }
    }
    ::v-deep.demo-scrollbar-list {
      overflow: auto !important;
    }
    .timeline-box {
      flex: 1;
      // height: 0;
      // overflow: auto;
      padding: 4px;
      .timeline-box-content {
        display: flex;
        flex: 1;
        justify-content: center;
      }
      .timeline-tag {
        font-size: 10px;
        transform: scale(0.8);
        border: 1px solid #d2d2d2;
        display: inline-block;
        padding: 0 2px;
        color: #777777;
      }
      .timeline-content {
        font-size: 12px;
        .timeline-ul {
          li {
            padding: 7px 0;
            border-bottom: 1px dashed #ccc;
          }
        }
      }
    }
    .fold-btn {
      position: absolute;
      top: 50%;
      right: 0px;
      width: 12px;
      height: 78px;
      margin-top: -39px;
      background: #e5e5e5;
      line-height: 78px;
      border-radius: 10px 0 0 10px;
      cursor: pointer;
    }
  }
}
.red {
  color: #e82f2f;
}
.orange {
  color: #fc9306;
}
.yellow {
  color: #eab909;
}
.heise {
  color: #333;
}
.blue {
  color: #1890ff;
  font-size: 14px;
  font-family: "SimHei";
  font-weight: 700;
  padding-top: 5px;
}
.infinite-list-item {
  ::v-deep .el-timeline-item__node--info {
    background-color: #ffff00 !important;
  }
  ::v-deep .el-timeline-item__wrapper {
    top: 0 !important;
  }
  ::v-deep .el-timeline-item__node {
    border: 2px solid #fff !important;
  }
  ::v-deep .el-timeline-item__tail {
    left: 6px !important;
  }
  ::v-deep .el-timeline-item__tail {
    padding: 5px 0;
    border-left: 2px solid #1890ff !important;
  }
}

.warning {
  width: 20px;
  height: 20px;
  display: inline-block;
  background: rgb(255, 133, 2);
  color: #fff;
  text-align: center;
  border-radius: 50%;
  margin-right: 5px;
  margin-bottom: 20px;
}
// 20220222 页面结构改造
.k-header-box {
  // height: 109px;
  position: relative;
  .add-task-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
  .top-box {
    margin-top: 0px;
    height: auto;
    // position: absolute;
    align-items: flex-start;
    background: #fff;
    .top-task-box {
      // background: #b1c0d1;
      // .el-button {
      //   display: none;
      // }
      position: static;
      box-shadow: none;
    }
  }
  // .top-box .top-task-box ul.task-list.topTaskVisible {
  //   height: auto;
  //   overflow-y: auto;
  // }
  .top-box .top-task-box ul.task-list {
    // height: auto;
    // min-height: 57px;
    // max-height: 300px;
    // flex-wrap: wrap;
    // overflow: hidden;
    li {
      margin-top: 4px;
      margin-bottom: 8px;
      padding: 4px 8px;

      border: 1px solid $line;
      border-radius: 4px;
    }
  }
  // .top-box .top-task-box ul.task-list li.active {
  //   background: none;
  //   border: 1px solid $primary;
  //   color: $primary;
  // }
  // .top-box .top-task-box ul.task-list li.active:hover{

  // }
  .top-box .top-task-box ul.task-list li .check::before {
    // background: #f00;

    border-top: 22px solid #f00;
    color: #fff;
    font-size: 14px;
  }
  .top-box .top-task-box ul.task-list li .check i {
    top: 0;
    right: 3px;
    font-size: 16px;
  }
}

.k-manager-header {
  font-size: 14px;
  line-height: 24px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  .task-status {
    margin-left: 8px;
    margin-right: 8px;
    position: relative;
    i {
      display: none;
    }
    i.danger {
      display: block;
      em {
        color: #ff4b53;
        position: absolute;
        width: 11px;
        height: 11px;
        border: none;
        background: #fff;
        font-size: 10px;
        line-height: 10px;
        border-radius: 50%;
        right: -1px;
        bottom: 0px;
      }
    }
    span {
      font-size: 18px;
      padding: 7px 8px 7px 6px;
      line-height: 26px;
    }
  }
  .right-flex {
    display: flex;
    flex-direction: column;
  }
  span {
    vertical-align: middle;
  }
  .project-title {
    flex: 1;
    font-size: 16px;
    display: inline-block;
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //溢出用省略号显示
    white-space: nowrap; //溢出不换行
    .short-title {
      width: 100%;
      max-width: 40em;
      display: inline-block;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
    }
  }
  .k-info {
    display: flex;
    align-items: center;
    .item {
      display: inline-block;
      padding-right: 40px;
    }
    i {
      padding-right: 2px;
    }
  }
}
.top-box {
  width: 100%;
  height: 50px;
  z-index: 9;
  position: relative;
  border-bottom: 1px solid $line;
  display: flex;
  align-items: center;
  flex-flow: row nowrap;
  justify-content: space-between;
  flex-direction: row;
  // h2 {
  //   font-size: 14px;
  //   line-height: 24px;
  //   margin-right: 8px;
  //   display: flex;
  //   .task-status {
  //     margin-left: 4px;
  //   }
  //   span {
  //     vertical-align: middle;
  //   }
  //   .project-title {
  //     flex: 1;
  //     display: inline-block;
  //     overflow: hidden; //超出的文本隐藏
  //     text-overflow: ellipsis; //溢出用省略号显示
  //     white-space: nowrap; //溢出不换行
  //     .short-title {
  //       width: 100%;
  //       max-width: 40em;
  //       display: inline-block;
  //       overflow: hidden; //超出的文本隐藏
  //       text-overflow: ellipsis; //溢出用省略号显示
  //       white-space: nowrap; //溢出不换行
  //     }
  //   }
  // }
  .top-btns {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  // 任务列表
  .top-task-box {
    position: absolute;
    bottom: -53px;
    width: 100%;
    left: 0;
    display: flex;
    align-items: center;
    background: #fff;
    box-shadow: 0px 3px 10px rgba($color: #000000, $alpha: 0.4);
    .visible-hide {
      visibility: hidden;
    }
    ul.task-list {
      height: 62px;
      margin-right: 10px;
      overflow: auto;
      display: flex;
      flex: 1;
      li {
        width: 300px;
        margin-right: 10px;
        padding: 0 12px;
        display: flex;
        align-items: center;
        position: relative;
        cursor: pointer;
        // justify-content: center;

        .check {
          // display: none;
          position: absolute;
          top: 0;
          right: 0px;
          width: 22px;
          height: 22px;
          color: #fff;
          &::before {
            position: absolute;
            top: 0;
            right: 0;
            content: "";
            height: 0;
            width: 0;
            overflow: hidden;
            font-size: 0;
            line-height: 0;
            border-top: 22px solid #1890ff;
            border-left: 22px solid transparent;
          }
          i {
            position: absolute;
            top: 1px;
            right: 2px;
            width: 10px;
            font-size: 10px;
            transform: scale(0.8);
          }
        }
        &.active {
          // background: #dbedff;
          background: #1890ff;
          color: #fff;
          .check {
            display: block;
          }
          &:hover {
            background: #1890ff;
            color: #fff;
          }
        }
        // &.active:hover {
        //   background: #dbedff;
        //   color: #555;
        // }
        &:hover {
          background: #f7fbff;
          color: #1890ff;
        }
        .task-status {
          // text-align: center;
          width: 24px;
          height: 24px;
          display: inline-block;
          position: relative;
          i {
            display: none;
          }
          i.danger {
            display: block;
            border-radius: 50%;
            position: absolute;
            top: 0;
            left: 0;
            width: 22px;
            height: 22px;
            border: 1px solid #ff4b53;
            em {
              color: #ff4b53;
              position: absolute;
              width: 11px;
              height: 11px;
              border: none;
              background: #fff;
              font-size: 10px;

              border-radius: 50%;
              right: -6px;
              bottom: 0px;
            }
          }
        }
        .info {
          flex: 1;
          padding-left: 8px;
          padding-right: 5px;
          line-height: 16px;
          padding: 4px;
          .text1,
          .text2 {
            width: 260px;
            display: inline-block;
            em {
              font-style: normal;
              vertical-align: middle;
              display: inline-block;
            }
            span {
              width: 215px;
              vertical-align: middle;
              display: inline-block;
              overflow: hidden; //超出的文本隐藏
              text-overflow: ellipsis; //溢出用省略号显示
              white-space: nowrap; //溢出不换行
            }
          }
        }
      }
    }
  }
}
.ui-mt {
  font-size: 14px;
  font-family: "SimHei";
  font-weight: bold;
}
.layout-time {
  // margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  // flex-direction: row-reverse;
}
.dialog-footer {
  text-align: right;
}
.layout-crad {
  // height: 340px;
}
.fold-card {
  height: 50px;
  overflow: hidden;
}
.record-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: inherit;
}
.record-list {
  flex: 1;
  overflow: initial;
  height: auto;
  // overflow: auto;
  // overflow: auto;
  // min-height: 200px;
  // .el-table {
  //   height: 100%;
  // }
  display: flex;
  flex-direction: column;
  .table-box {
    overflow: auto;
  }
}
.info-box {
  padding-left: 28px;
  position: relative;
  i {
    position: absolute;
    top: 0;
    left: 0;
    color: #e6ad00;
    font-size: 18px;
    vertical-align: top;
  }
}
.upload {
  ::v-deep .el-upload {
    display: none;
  }
  ::v-deep .el-upload-list {
    li:first-child {
      margin-top: 5px;
    }
  }
}
</style>

<style lang="scss">
.k-header-box {
  .el-tabs__content {
    height: 4px;
    font-size: 1px;
  }
}
.timeline-box {
  display: flex;
  height: calc(100% - 63px);
  box-sizing: border-box;
  .el-scrollbar {
    width: 517px;
  }
  .el-scrollbar__wrap {
    height: 100% !important;
  }
  .el-scrollbar__thumb {
    height: 0 !important;
  }
}
</style>
